<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="80%">
    <el-form ref="formRef" :model="formData" :rules="formRules" v-loading="formLoading">
      <el-form-item label="样本名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入风险名称"/>
      </el-form-item>
      <el-form-item label="风险类型" prop="riskType" class="w-80">
        <el-select
          v-model="formData.riskType" placeholder="请选择风险类型" @change="refreshRiskList"
          :disabled="formType !== 'create'">
          <el-option
            :label="value" :value="Number(key)" :key="key"
            v-for="(value, key) in riskTypeDict"/>
        </el-select>
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input v-model="formData.description" type="textarea" placeholder="请输入描述"/>
      </el-form-item>
      <el-form-item>
        <div class="w-full flex justify-end">
          <el-button type="primary" @click="addRiskTarget">新增风险</el-button>
        </div>
      </el-form-item>
      <el-collapse expand-icon-position="left" v-model="collapseValues">
        <Draggable v-model="formData.riskDetail" :min="2">
        <template #default="{ element: item, index }">
          <el-collapse-item
            :name="index" :title="item?.riskTarget || '风险对象'" :key="item.id">
            <div class="flex flex-col gap-2">
            <el-card class="w-full" shadow="hover">
              <template #header>
                <div class="card-header">
                  <div class="w-full justify-end flex ">
                    <el-button
                      type="text" :icon="Close" style="margin-top: -10px;margin-right: -5px"
                      @click="removeIdentifyObject(index)"/>
                  </div>
                  <div>
                    风险对象:
                    <el-input
                      v-model="item.riskTarget" placeholder="请输入风险对象"
                      style="width: 200px"/>
                    <el-button
                      type="primary" @click="add_content(item, index)"
                      class="float-right">
                      新增内容
                    </el-button>
                  </div>
                </div>
              </template>
              <el-table :data="item.contents" style="width: 100%">
                <el-table-column label="编码" align="center" prop="identifyContentCode">
                  <template #default="{ row }">
                    <el-input
                      disabled v-model="row.identifyContentCode"
                      placeholder="请输入辨识内容编码"/>
                  </template>
                </el-table-column>
                <el-table-column label="辨识内容" align="center" prop="identifyContent">
                  <template #default="{ row }">
                    <el-input v-model="row.identifyContent" placeholder="请输入辨识内容"/>
                  </template>
                </el-table-column>
                <el-table-column prop="hazard" label="危害">
                  <template #default="{ row }">
                    <el-select
                      v-model="row.hazard"
                      placeholder="请选择危害类型"
                      style="width: 100%"
                    >
                      <el-option
                        v-for="(value, key) in hazardList"
                        :key="key"
                        :label="value"
                        :value="key"
                      />
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column prop="projectSolution" label="工程解决方案">
                  <template #default="{ row }">
                    <el-input v-model="row.projectSolution" placeholder="请输入工程解决方案"/>
                  </template>
                </el-table-column>
                <el-table-column prop="managerSolution" label="管理解决方案">
                  <template #default="{ row }">
                    <el-input v-model="row.managerSolution" placeholder="请输入管理解决方案"/>
                  </template>
                </el-table-column>
                <el-table-column prop="selfSolution" label="个人解决方案">
                  <template #default="{ row }">
                    <el-input v-model="row.selfSolution" placeholder="请输入个人解决方案"/>
                  </template>
                </el-table-column>
                <el-table-column prop="trainEduSolution" label="培训教育方案">
                  <template #default="{ row }">
                    <el-input v-model="row.trainEduSolution" placeholder="请输入培训教育方案"/>
                  </template>
                </el-table-column>
                <el-table-column prop="badSolution" label="应急解决方案字段">
                  <template #default="{ row }">
                    <el-input v-model="row.badSolution" placeholder="请输入应急解决方案字段"/>
                  </template>
                </el-table-column>
                <el-table-column label="操作" align="center">
                  <template #default="{ $index }">
                    <el-button
                      type="primary" :icon="Delete"
                      @click="del_content(index, $index)"/>
                  </template>
                </el-table-column>
              </el-table>
            </el-card>
          </div>
          </el-collapse-item>
        </template>
      </Draggable>
      </el-collapse>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">

import {Delete, Close} from '@element-plus/icons-vue';
import {hazardList, riskTypeBizCodePREFIXDict, riskTypeDict} from '@/utils/dict';
import pinyin from 'pinyin';
import {RiskSampleApi, RiskSampleVO} from '@/api/zjyj/risksample';
import Draggable from '@/components/Draggable/index.vue';

/** 风险辨识 表单 */
defineOptions({name: 'SampleForm'});

const {t} = useI18n(); // 国际化
const message = useMessage(); // 消息弹窗

const dialogVisible = ref(false); // 弹窗的是否展示
const dialogTitle = ref(''); // 弹窗的标题
const formLoading = ref(false); // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref(''); // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  riskType: undefined,
  name: undefined,
  description: undefined,
  riskDetail: []
});
const formRules = reactive({
  riskType: [{required: true, message: '风险类型不能为空', trigger: 'change'}],
  riskTypeInfoId: [{required: true, message: '风险点不能为空', trigger: 'blur'}],
  riskTarget: [{required: true, message: '风险对象不能为空', trigger: 'blur'}],
  identifyContent: [{required: true, message: '辨识内容不能为空', trigger: 'blur'}]
});
const formRef = ref(); // 表单 Ref

const collapseValues = ref([]);

const add_content = async (data, object_index) => {
  // formData.value.contents.增加一个空对象
  if (data.contents == undefined) {
    data.contents = [];
  }
  data.contents.push({
    identifyContent: '',
    identifyContentCode: contentCodeInit(formData.value.riskType, object_index, data.contents.length),
    hazard: '',
    projectSolution: '',
    managerSolution: '',
    selfSolution: '',
    trainEduSolution: '',
    badSolution: '',
  });
};
const del_content = async (object_index: number, index: number) => {
  console.log('del_content', index, formData.value?.identifyObjects[object_index]);
  formData.value?.identifyObjects[object_index].contents.splice(index, 1);
};

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true;
  dialogTitle.value = t('action.' + type);
  formType.value = type;
  resetForm();
  // 修改时，设置数据
  if (id) {
    formLoading.value = true;
    try {
      formData.value = await RiskSampleApi.getRiskSample(id);
      // 遍历 formData.value.identifyObjects，给每个 identifyObjects 增加一个 contents 数组
      resetCollapseValues();
    } finally {
      formLoading.value = false;
    }
  }
};
defineExpose({open}); // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']); // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate();
  // 提交请求
  formLoading.value = true;
  try {
    const data = formData.value;
    if (formType.value === 'create') {
      await RiskSampleApi.createRiskSample(data);
      message.success(t('common.createSuccess'));
    } else {
      await RiskSampleApi.updateRiskSample(data as RiskSampleVO);
      message.success(t('common.updateSuccess'));
    }
    dialogVisible.value = false;
    // 发送操作成功的事件
    emit('success');
  } finally {
    formLoading.value = false;
  }
};
const resetCollapseValues = () => {
  collapseValues.value = [];
  if (formData.value?.riskDetail == undefined) {
    return;
  }
  formData.value?.riskDetail.forEach((_item, index) => {
    collapseValues.value.push(index);
  });
};

const addRiskTarget = async () => {
  formData.value?.riskDetail.push({});
  resetCollapseValues();
};
/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    riskType: undefined,
    name: undefined,
    description: undefined,
    riskDetail: [{}]
  };
  formRef.value?.resetFields();
  collapseValues.value = [0];
};


const removeIdentifyObject = async (index) => {
  await message.delConfirm();
  formData.value.riskDetail.splice(index, 1);
};

// 删除以下未使用的变量和方法
const riskInfoName = ref('');

const contentCodeInit = (riskType, objectIndex, contentSize) => {
  const prefix = riskTypeBizCodePREFIXDict[riskType];
  const initials = pinyin(riskInfoName.value, {
    style: pinyin.STYLE_FIRST_LETTER,
    heteronym: false
  }).map(item => item[0].toUpperCase()).join('');
  const paddedObjectIndex = String(objectIndex + 1).padStart(2, '0');
  const paddedContentSize = String(contentSize + 1).padStart(3, '0');
  return `${prefix}${initials}${paddedObjectIndex}${paddedContentSize}`;
};
</script>

<style scoped>
:deep(.el-card__header) {
  padding: 10px;
}
</style>
